package Logic.GeneralManagerLogic;

import java.rmi.RemoteException;
import java.util.ArrayList;

import Po.Discount;
import Po.Equivalent;
import Po.Promotion;
import RemoteServerInterface.GeneralManagerServerInterface;
import Start.GeneralManagerMain;
import VO.DiscountVO;
import VO.EquivalentVO;

public class GeneralManagerPromotionLogic {

	private static GeneralManagerPromotionLogic instance;
	static GeneralManagerServerInterface server = GeneralManagerMain.getManagerServer();
	Discount[] discountList;
	Equivalent[] equivalentList;
	
	public int[] gerEquivalentIdList(){
		if(equivalentList==null)
			return null;
		int[] tmp = new int[equivalentList.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i] = equivalentList[i].ID;
		}
		return tmp;
	}
	
	public int[] gerDiscountIdList(){
		if(discountList==null)
			return null;
		int[] tmp = new int[discountList.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i] = discountList[i].ID;
		}
		return tmp;
	}
	
	public static GeneralManagerServerInterface getServer(){
		return server;
	}
	
	public static GeneralManagerPromotionLogic getInstance(){
		if(instance==null)
			instance = new GeneralManagerPromotionLogic();
		return instance;
	}
	
	private GeneralManagerPromotionLogic(){
		super();
	}
	
	public int createDiscount(DiscountVO d) throws RemoteException{
		server.addDiscountPromotion(d.toDiscountPO());
		return 0;
	}
	
	public int createEquivalent(EquivalentVO e) throws RemoteException{
		server.addEquivalentPromotion(e.toEquivalentPO());
		return 0;
	}
	
	public Equivalent[] getAllEquivalents(){
		return equivalentList;
	}
	
	public Discount[] getAllDiscounts(){
		return discountList;
	}
	
	public void updateAllPromotion() throws RemoteException{
		ArrayList<Promotion> tmp = server.getPromotions();
		int k=0,l=0;
		for(int i=0;i<tmp.size();i++){
			if(tmp.get(i) instanceof Discount){
				k++;
			}else{
				l++;
			}
		}
		discountList = new Discount[k];
		equivalentList = new Equivalent[l];
		k=0;l=0;
		for(int i=0;i<tmp.size();i++){
			if(tmp.get(i) instanceof Discount){
				discountList[k] = (Discount)tmp.get(i);
				k++;
			}else if(tmp.get(i) instanceof Equivalent){
				equivalentList[l] = (Equivalent)tmp.get(i);
				l++;
			}
		}
		return;
	}
	
	public EquivalentVO getEquivalent(int id){
		if(equivalentList==null)
			return null;
		
		for(int i=0;i<equivalentList.length;i++){
			if(equivalentList[i].ID == id)
				return EquivalentVO.toEquivalentVO(equivalentList[i]);
			
		}
		
		return null;
	}
	
	
	public DiscountVO getDiscount(int id){
		if(discountList==null)
			return null;
		
		for(int i=0;i<discountList.length;i++){
			if(discountList[i].ID == id)
				return DiscountVO.toDiscountVO(discountList[i]);
			
		}
		
		return null;
	}
}
